#include <QSqlRecord>
#include <QSqlField>
#include <QSqlTableModel>
#include <QIcon>
#include "contactsqlmodel.h"


ContactSqlModel::ContactSqlModel(QObject *parent)
        : QSqlTableModel(parent)
{
    setEditStrategy(QSqlTableModel::OnRowChange);
    setTable("contacts");
    setSort(fieldIndex("name"),Qt::AscendingOrder);
    select();
}

QVariant ContactSqlModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid())
        return QVariant();

    QVariant value = QSqlQueryModel::data(index, role);
    if(role > Qt::UserRole) {
        QSqlRecord record = QSqlTableModel::record(index.row());
        if(role == EmailAdress)
            return record.value(record.indexOf("email"));
        if(role == NumberAdress)
            return record.value(record.indexOf("phone"));
        if(role == ID)
            return record.value(record.indexOf("id"));
    }
    if(role == Qt::DecorationRole) {
        QSqlRecord record = QSqlQueryModel::record(index.row());
        return record.value(record.indexOf("face"));
    }
    return value;
}

QString ContactSqlModel::getEmailAdress(const QModelIndex &index) const
{
    QVariant emailAdress = data(index,EmailAdress);
    //phoneNumber.toString();
    return emailAdress.toString();
}

bool ContactSqlModel::hasPhone(const QModelIndex &index) const
{
    QVariant phoneNumber = data(index,NumberAdress);
    //phoneNumber.toString();
    return !phoneNumber.isNull();
}

bool ContactSqlModel::hasMessenger(const QModelIndex &index) const
{
    QVariant messengerAdress = data(index,XMPPAdress);
    //messengerAdress.toString();
    return !messengerAdress.isNull();
}
